<script setup>
	import {
		Position,
		Handle,
		useNode
	} from '@vue-flow/core'
    import {
        ref,
        watch,
        onMounted,
        provide, inject
    } from "vue";
	import FunctionManagement from "@/views/function_call/cpns/param-management/index.vue";
	// import {
	// 	Close
	// } from "@vicons/ionicons5";
	import {
		JBoltApi
	} from "@/service/request/index.js";
	import AiChatSetting from './cnps/AiChatSetting.vue';

	const props = defineProps(['id', 'data']) //默认配置

	const {
		node
	} = useNode()
	provide('currentNodeId', props.id);


	const defaultFuncIdsConfig = ref({
		functionList: []
	})

	//选择function
	function handleDrawerYesClick({
		componentRef,
		close
	}) {
		componentRef.submit((data) => {
			props.data.funcCallConfig.functions = data.map(item => item.id);
			defaultFuncIdsConfig.value.functionList = data;
			close();
		})
	}

	//移除function
	function handleRemoveItem(item) {
		console.log(item.id, "移除item")
		// 从选中列表中移除
		props.data.funcCallConfig.functions = props.data.funcCallConfig.functions.filter(i => i !== item.id)
		defaultFuncIdsConfig.value.functionList = defaultFuncIdsConfig.value.functionList.filter(i => i.id !== item.id)
	}

	// 监听props.data的变化
    const updateNodesData = inject("updateNodesData")
    // 监听props.data的变化
    watch(() => props.data, (newValue, oldValue) => {
        console.log('props.data changed ', newValue);
        updateNodesData();
    }, {
        deep: true
    })

	function getAllFunctionList() {
		const functions = props.data.funcCallConfig.functions;
		if (!functions || functions.length === 0) {
			return;
		} else {
			JBoltApi.tryGet(`/aiFunction/list`).then(res => {
				const all = res.data; // 全部数据的数组
				// 选中 ID 的数组
				// 筛选出 all 中 id 存在于 functions 数组中的对象
				const filteredData = all.filter(item => functions.includes(item.id));
				defaultFuncIdsConfig.value.functionList = filteredData.map(item => {
					return {
						id: item.id,
						sn: item.sn,
						briefInfo: item.briefInfo
					}
				})
			}).catch((err) => {
                console.error(err);
            })
		}

	}

	onMounted(() => {
		getAllFunctionList();
	})
</script>

<template>
	<div class="_container">
		<div class="fx fx-c_center pad-16 header">
			<div class="fx fx-center wh-40 logo">
				<jb-icon :local="true" icon="gravity-ui:function" width="30" color="#22c55e"></jb-icon>
			</div>
			<div class="ml-10 tc-dark">
				<div>Function调用</div>
				<p class="font-12 tc-assist">调用本地函数生成数据</p>
			</div>
		</div>
		<div class="form fx-col pad-16 ">
			<div class="fx-m_between">
				<div class="fx fx-m_between" style="margin-bottom: 8px">
					<div>Function资源</div>
					<div>
						<jb-btn quaternary round type="primary" ghost :drawerComponent="FunctionManagement"
							:drawerComponentProps="{selectList:defaultFuncIdsConfig.functionList}"
							:drawerArgs="{width: '1200px'}" size="tiny"
							@drawerYesClick="handleDrawerYesClick">选择Function资源
						</jb-btn>
					</div>
				</div>
				<div collapse-mode="width" :collapsed-width="0" :width="300">
					<div class="selected-items-container">

						<div @wheel.stop class="tale-div">
							<template v-if="defaultFuncIdsConfig.functionList.length">
								<jb-table class="full-height-table" ref="tableRef"
									:row-config="{keyField: 'id', isHover: true}"
									:data="defaultFuncIdsConfig.functionList" >
									<jb-column type="seq" title="序号" width="60" fixed="left"></jb-column>
									<jb-column field="sn" title="编号" min-width="100" fixed="left"></jb-column>
									<jb-column field="briefInfo" title="简介" min-width="160"></jb-column>
									<jb-column title="操作" width="80" fixed="right">
										<template #default="{row}">
											<n-button circle size="tiny" strong secondary type="error"
												class="delete-btn" @click="handleRemoveItem(row)">
												<template #icon>
                          <jb-icon :local="true" icon="ri:subtract-fill" color="red"></jb-icon>
<!--													<n-icon>-->
<!--														<close />-->
<!--													</n-icon>-->
												</template>
											</n-button>
										</template>
									</jb-column>
								</jb-table>
							</template>
							<div v-else class="empty-text">
								暂无选中项
							</div>
						</div>
					</div>
				</div>
			</div>
			<!--      <label>AI 模型</label>-->
			<!--      <jb-select url="aiResource/listAllEnabledType" labelField="name" placeholder="请选择AI模型"-->
			<!--                 valueField="sn" v-model:value="props.data.modelType"></jb-select>-->
			<AiChatSetting v-model="props.data.llmConfig"
				:out="['modelType', 'promptTpl']"
				:inner="['systemRole','maxTokens', 'temperature', 'topP', 'topK']"  />

		</div>
		<div class="footer pad-16">
			<p class="tc-gray ">输出字段</p>
            <div class="output mt-8 pad-8 fx fx-c_center fx-m_between">
                <div class="fx fx-c_center">
                    <div class="output-flag noshrink"></div>
                    <n-input v-model:value="props.data.funcCallConfig.matchFuncOutputField" placeholder="字段名"
                             class="tc-gray ml-8 w-140"></n-input>
                </div>
                <span class="tc-assist">匹配到的function编号和描述</span>
            </div>
			<div class="output mt-8 pad-8 fx fx-c_center fx-m_between">
				<div class="fx fx-c_center">
					<div class="output-flag noshrink"></div>
					<n-input v-model:value="props.data.funcCallConfig.resultOutputField" placeholder="字段名"
						class="tc-gray ml-8 w-140"></n-input>
				</div>
				<span class="tc-assist">function执行的结果</span>
			</div>

		</div>

		<Handle type="target" :position="Position.Left" />
		<Handle type="source" id="func_call_success" :position="Position.Right"
			style="transform: translate(50%, calc(-50% - 130px))" class="handle_success" />
        <Handle type="source" id="func_no_match" :position="Position.Right"
                style="transform: translate(50%, calc(-50% - 50px))" class="handle_warn"/>
		<Handle type="source" id="fail" :position="Position.Right"
			style="transform: translate(50%, calc(-50% + 30px))" />


	</div>
</template>

<style scoped lang="scss">
	._container {
		background-color: #fff;
		border: 1px solid #e5e7eb;
		border-radius: 12px;
		box-sizing: border-box;
		width: 500px;
		box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.1) 0px 4px 6px -4px;
	}

	.header,
	.form {
		border-bottom: 1px solid rgb(229, 231, 235);
	}

	.logo {
		background: #dcfce7;
		border-radius: 12px;
	}

	label {
		margin-bottom: 8px;
	}

	label:not(:first-child) {
		margin-top: 16px;
	}

	.output {
		background: rgb(249, 250, 251);
		border-radius: 12px;
	}

	.output-flag {
		width: 8px;
		height: 8px;
		border-radius: 50%;
		background: #22c55e;
	}

	.more_btn {
		background: #f9fafb;
		padding: 8px;
		margin-top: 16px;
		cursor: pointer;
		border-radius: 6px;
	}


	.empty-text {
		color: #c2c2c2;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 150px;
		border: 1px solid rgb(229, 231, 235);
		border-radius: 5px;

	}

	.tale-div {
		margin-bottom: 10px;
	}


</style>